using System;
using System.Collections.Generic;
using System.Linq;
using BanZuiCloudControlAgent.Core.Tasks.Base;
using BanZuiCloudControlAgent.Core.Tasks.Enums;

namespace BanZuiCloudControlAgent.Core.Tasks.Queue
{
    /// <summary>
    /// 优先级任务队列，用于根据优先级排序任务
    /// </summary>
    public class PriorityTaskQueue
    {
        /// <summary>
        /// 任务优先级队列
        /// </summary>
        private readonly Dictionary<TaskPriority, Queue<BaseTask>> _priorityQueues;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public PriorityTaskQueue()
        {
            _priorityQueues = new Dictionary<TaskPriority, Queue<BaseTask>>();
            
            // 初始化所有优先级的队列
            foreach (TaskPriority priority in Enum.GetValues(typeof(TaskPriority)))
            {
                _priorityQueues[priority] = new Queue<BaseTask>();
            }
        }
        
        /// <summary>
        /// 入队
        /// </summary>
        /// <param name="task">任务</param>
        public void Enqueue(BaseTask task)
        {
            if (task == null)
            {
                throw new ArgumentNullException(nameof(task));
            }
            
            _priorityQueues[task.Priority].Enqueue(task);
        }
        
        /// <summary>
        /// 出队
        /// </summary>
        /// <returns>任务</returns>
        public BaseTask Dequeue()
        {
            // 从高优先级到低优先级查找任务
            foreach (TaskPriority priority in Enum.GetValues(typeof(TaskPriority)).Cast<TaskPriority>().OrderByDescending(p => p))
            {
                if (_priorityQueues[priority].Count > 0)
                {
                    return _priorityQueues[priority].Dequeue();
                }
            }
            
            return null;
        }
        
        /// <summary>
        /// 尝试出队
        /// </summary>
        /// <param name="task">任务</param>
        /// <returns>是否成功</returns>
        public bool TryDequeue(out BaseTask task)
        {
            task = Dequeue();
            return task != null;
        }
        
        /// <summary>
        /// 获取任务数量
        /// </summary>
        public int Count
        {
            get { return _priorityQueues.Values.Sum(q => q.Count); }
        }
        
        /// <summary>
        /// 获取指定优先级的任务数量
        /// </summary>
        /// <param name="priority">优先级</param>
        /// <returns>任务数量</returns>
        public int GetCount(TaskPriority priority)
        {
            return _priorityQueues[priority].Count;
        }
        
        /// <summary>
        /// 清空队列
        /// </summary>
        public void Clear()
        {
            foreach (var queue in _priorityQueues.Values)
            {
                queue.Clear();
            }
        }
    }
} 